<template>
  <div class="approval-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>审批中心</span>
          <el-badge :value="pendingCount" :max="99" class="badge">
            <el-button type="primary" @click="fetchData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </el-badge>
        </div>
      </template>

      <!-- 筛选区域 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="申请类型">
          <el-select v-model="queryForm.applyType" placeholder="全部" clearable style="width: 150px">
            <el-option label="学籍异动" :value="1" />
            <el-option label="信息修改" :value="2" />
            <el-option label="档案附件" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 150px">
            <el-option label="待审批" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card pending">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ pendingCount }}</div>
                <div class="stat-label">待审批</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card approved">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ approvedCount }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card rejected">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ rejectedCount }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card total">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><DocumentCopy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ totalCount }}</div>
                <div class="stat-label">全部申请</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%; margin-top: 20px"
        border
      >
        <el-table-column prop="id" label="申请ID" width="80" />
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="applyType" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getApplyTypeTag(row.applyType)">
              {{ getApplyTypeText(row.applyType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="申请内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="approvalLevel" label="审批级别" width="150" align="center">
          <template #default="{ row }">
            <el-tag :type="getApprovalLevelTag(row.approvalLevel)" size="small">
              {{ row.approvalLevel === 1 ? 'Level 1 初审' : 'Level 2 终审' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="attachmentCount" label="附件" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.attachmentCount > 0" type="info" size="small">
              <el-icon><Paperclip /></el-icon>
              {{ row.attachmentCount }}
            </el-tag>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              link 
              type="success" 
              size="small" 
              @click="handleApprove(row)" 
              v-if="canApprove(row)"
            >
              通过
            </el-button>
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="handleReject(row)" 
              v-if="canApprove(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.current"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border v-if="currentRow">
        <el-descriptions-item label="申请ID">{{ currentRow.id }}</el-descriptions-item>
        <el-descriptions-item label="学生姓名">{{ currentRow.studentName }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ currentRow.studentNo }}</el-descriptions-item>
        <el-descriptions-item label="申请类型">
          <el-tag :type="getApplyTypeTag(currentRow.applyType)">
            {{ getApplyTypeText(currentRow.applyType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间" :span="2">
          {{ currentRow.applyTime }}
        </el-descriptions-item>
        
        <!-- 审批级别信息 -->
        <el-descriptions-item label="当前审批级别" :span="2">
          <el-tag :type="getApprovalLevelTag(currentRow.approvalLevel)" size="large">
            {{ getApprovalLevelText(currentRow.approvalLevel) }}
          </el-tag>
          <span style="margin-left: 10px; color: #909399; font-size: 13px;">
            {{ getApprovalLevelDesc(currentRow.approvalLevel) }}
          </span>
        </el-descriptions-item>
        
        <el-descriptions-item label="申请内容" :span="2">
          {{ currentRow.content }}
        </el-descriptions-item>
        <el-descriptions-item label="审批状态" :span="2">
          <el-tag :type="getStatusTag(currentRow.status)">
            {{ getStatusText(currentRow.status) }}
          </el-tag>
        </el-descriptions-item>
        
        <!-- 审批人信息 -->
        <el-descriptions-item label="审批人" v-if="currentRow.approverName">
          {{ currentRow.approverName }}
        </el-descriptions-item>
        <el-descriptions-item label="审批时间" v-if="currentRow.approveTime">
          {{ currentRow.approveTime }}
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" :span="2" v-if="currentRow.remark">
          {{ currentRow.remark }}
        </el-descriptions-item>
        
        <el-descriptions-item label="附件材料" :span="2" v-if="currentRow.attachmentCount > 0">
          <el-link 
            type="primary" 
            :underline="false" 
            @click="viewDetailDialog"
          >
            <el-icon><Paperclip /></el-icon>
            查看 {{ currentRow.attachmentCount }} 个附件
          </el-link>
        </el-descriptions-item>
      </el-descriptions>

      <el-form 
        v-if="isApproving" 
        :model="approvalForm" 
        label-width="90px" 
        style="margin-top: 20px"
      >
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
          <el-button 
            type="success" 
            @click="confirmApprove" 
            :loading="submitLoading" 
            v-if="isApproving && approvalForm.status === 1"
            size="large"
          >
            <el-icon><CircleCheck /></el-icon>
            确认通过
          </el-button>
          <el-button 
            type="danger" 
            @click="confirmReject" 
            :loading="submitLoading" 
            v-if="isApproving && approvalForm.status === 2"
            size="large"
          >
            <el-icon><CircleClose /></el-icon>
            确认拒绝
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框（含附件） -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="900px"
    >
      <ApprovalDetail v-if="currentApprovalId" :approval-id="currentApprovalId" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  RefreshLeft, 
  Clock, 
  CircleCheck, 
  CircleClose, 
  DocumentCopy, 
  Close,
  Paperclip 
} from '@element-plus/icons-vue'
import { getApprovalPage, approveApply, rejectApply, getApprovalStatistics } from '@/api/approval'
import ApprovalDetail from '../student/components/ApprovalDetail.vue'
import { useUserStore } from '@/store/user'

const route = useRoute()
const userStore = useUserStore()

interface ApprovalItem {
  id: number
  studentId: number
  studentName: string
  studentNo: string
  applyType: number
  content: string
  status: number
  applyTime: string
  approveTime?: string
  remark?: string
  attachmentCount?: number
  approvalLevel?: number  // 审批级别：1-初审 2-终审
  approverName?: string   // 审批人姓名
}

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  applyType: undefined as number | undefined,
  status: undefined as number | undefined
})

// 表格数据
const tableData = ref<ApprovalItem[]>([])
const total = ref(0)
const loading = ref(false)

// 统计数据
const pendingCount = ref(0)
const approvedCount = ref(0)
const rejectedCount = ref(0)
const totalCount = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('审批详情')
const currentRow = ref<ApprovalItem | null>(null)
const isApproving = ref(false)
const submitLoading = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const currentApprovalId = ref<number | null>(null)

// 审批表单
const approvalForm = reactive({
  status: 0,
  remark: ''
})

// 申请类型文本
const getApplyTypeText = (type: number) => {
  const map: Record<number, string> = {
    1: '学籍异动',
    2: '信息修改',
    3: '档案附件'
  }
  return map[type] || '未知'
}

// 申请类型标签
const getApplyTypeTag = (type: number) => {
  const map: Record<number, string> = {
    1: 'warning',
    2: '',
    3: 'info'
  }
  return map[type] || ''
}

// 状态文本
const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '待审批',
    1: '已通过',
    2: '已拒绝'
  }
  return map[status] || '未知'
}

// 状态标签
const getStatusTag = (status: number) => {
  const map: Record<number, string> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || ''
}

// 审批级别文本
const getApprovalLevelText = (level?: number) => {
  const map: Record<number, string> = {
    1: 'Level 1 - 班主任初审',
    2: 'Level 2 - 教务处终审'
  }
  return map[level || 1] || '未知'
}

// 审批级别标签
const getApprovalLevelTag = (level?: number) => {
  const map: Record<number, string> = {
    1: '',
    2: 'warning'
  }
  return map[level || 1] || ''
}

// 审批级别描述
const getApprovalLevelDesc = (level?: number) => {
  const map: Record<number, string> = {
    1: '需要班主任进行初审',
    2: '初审已通过，需要教务处进行终审'
  }
  return map[level || 1] || ''
}

// 判断当前用户是否可以审批该申请
const canApprove = (row: ApprovalItem) => {
  // 只有待审批状态才能审批
  if (row.status !== 0) {
    return false
  }
  
  const currentRole = userStore.userInfo?.roleCode
  const approvalLevel = row.approvalLevel || 1
  
  // Level 1（初审）：只有教师可以审批
  if (approvalLevel === 1 && currentRole === 'teacher') {
    return true
  }
  
  // Level 2（终审）：只有管理员可以审批
  if (approvalLevel === 2 && currentRole === 'admin') {
    return true
  }
  
  return false
}

// 获取列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const data = await getApprovalPage(queryForm)
    tableData.value = data.records || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取审批列表失败', error)
    ElMessage.error('获取审批列表失败')
  } finally {
    loading.value = false
  }
  
  // 获取统计数据
  fetchStatistics()
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const stats = await getApprovalStatistics()
    pendingCount.value = stats.pendingCount || 0
    approvedCount.value = stats.approvedCount || 0
    rejectedCount.value = stats.rejectedCount || 0
    totalCount.value = stats.totalCount || 0
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryForm.applyType = undefined
  queryForm.status = undefined
  handleQuery()
}

// 查看
const handleView = (row: ApprovalItem) => {
  currentRow.value = row
  dialogTitle.value = '审批详情'
  isApproving.value = false
  dialogVisible.value = true
}

// 通过
const handleApprove = (row: ApprovalItem) => {
  currentRow.value = row
  dialogTitle.value = '审批通过'
  isApproving.value = true
  approvalForm.status = 1
  approvalForm.remark = ''
  dialogVisible.value = true
}

// 拒绝
const handleReject = (row: ApprovalItem) => {
  currentRow.value = row
  dialogTitle.value = '审批拒绝'
  isApproving.value = true
  approvalForm.status = 2
  approvalForm.remark = ''
  dialogVisible.value = true
}

// 查看详情（含附件）
const viewDetailDialog = () => {
  if (!currentRow.value) return
  currentApprovalId.value = currentRow.value.id
  detailDialogVisible.value = true
}

// 确认通过
const confirmApprove = async () => {
  if (!currentRow.value) return
  
  submitLoading.value = true
  try {
    await approveApply({
      id: currentRow.value.id,
      status: 1,
      remark: approvalForm.remark
    })
    
    ElMessage.success('审批通过')
    dialogVisible.value = false
    fetchData()
  } catch (error: any) {
    console.error('审批失败', error)
    ElMessage.error(error.response?.data?.msg || '审批失败')
  } finally {
    submitLoading.value = false
  }
}

// 确认拒绝
const confirmReject = async () => {
  if (!approvalForm.remark || !approvalForm.remark.trim()) {
    ElMessage.warning('请填写拒绝原因')
    return
  }
  
  if (!currentRow.value) return
  
  submitLoading.value = true
  try {
    await rejectApply({
      id: currentRow.value.id,
      status: 2,
      remark: approvalForm.remark
    })
    
    ElMessage.success('已拒绝申请')
    dialogVisible.value = false
    fetchData()
  } catch (error: any) {
    console.error('审批失败', error)
    ElMessage.error(error.response?.data?.msg || '审批失败')
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  await fetchData()
  
  // 检查路由参数，如果有 approvalId，则自动打开详情
  const approvalId = route.query.approvalId
  if (approvalId) {
    currentApprovalId.value = Number(approvalId)
    detailDialogVisible.value = true
  }
})
</script>

<style scoped lang="scss">
.approval-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .badge {
      :deep(.el-badge__content) {
        font-weight: bold;
      }
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .stats-cards {
    margin-bottom: 20px;

    .stat-card {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      .stat-content {
        display: flex;
        align-items: center;
        gap: 20px;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 30px;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 5px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }

      &.pending {
        .stat-icon {
          background: #fdf6ec;
          color: #e6a23c;
        }
        .stat-value {
          color: #e6a23c;
        }
      }

      &.approved {
        .stat-icon {
          background: #f0f9ff;
          color: #67c23a;
        }
        .stat-value {
          color: #67c23a;
        }
      }

      &.rejected {
        .stat-icon {
          background: #fef0f0;
          color: #f56c6c;
        }
        .stat-value {
          color: #f56c6c;
        }
      }

      &.total {
        .stat-icon {
          background: #f4f4f5;
          color: #909399;
        }
        .stat-value {
          color: #303133;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

